package com.atguigu.msmservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.commonutils.RandomUtil;
import com.atguigu.msmservice.service.MsMService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

//@CrossOrigin
@RestController
@RequestMapping("/edumsm/msm")
public class MsmController {


    @Autowired
    private MsMService msMService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;



    @ApiOperation(value = "通过手机号获取验证码")
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){

        //1 从redis获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }

        //2 如果redis获取 不到，进行阿里云发送
        //生成随机值，传递阿里云进行发送
        code = RandomUtil.getFourBitRandom();
        HashMap<String, Object> param = new HashMap<>();

        param.put("code", code);
        //调用service发送短信的方法
        boolean isSend =  msMService.send(param, phone);
        if (isSend){

            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.ok();

        }else{
            return R.error().message("发送短信失败");
        }


    }


}
